/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDelta;
import com.velocityme.entity.Project;
import com.velocityme.enums.ChangeDeltaItemType;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class ProjectBean implements ProjectLocal {
    @EJB
    private ActivityLocal activityBean;

    @PersistenceContext
    private EntityManager em;

    public Project findProject(KeyLocal key, Long projectId) {
        Project project = em.find(Project.class, projectId);
        key.assertHasPermission(project, Permission.NODE_VIEW);
        return project;
    }

    public Project createProject(KeyLocal key, Project project, boolean interested) {
        key.assertHasPermission(project.getParentNode(), Permission.PROJECT_CREATE);
        ChangeDelta changeDelta = project.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        activityBean.logCreate(key, project, changeDelta, interested);
        changeDelta.addItem(ChangeDeltaItemType.SPONSOR, project.getSponsor().toString());
        changeDelta.addItem(ChangeDeltaItemType.PRIMARY_CONTACT, project.getPrimaryContact().toString());
        em.persist(project);
        em.persist(changeDelta);
        return project;
    }

    public void editProject(KeyLocal key, Project project) {
        Project current = em.find(Project.class, project.getId());
        key.assertHasPermission(project, Permission.PROJECT_EDIT);
        ChangeDelta changeDelta = project.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        activityBean.logEdit(key, project, current, changeDelta);
        if (!project.getSponsor().equals(current.getSponsor())) {
            changeDelta.addItem(ChangeDeltaItemType.SPONSOR, project.getSponsor().toString());
        }
        if (!project.getPrimaryContact().equals(current.getPrimaryContact())) {
            changeDelta.addItem(ChangeDeltaItemType.PRIMARY_CONTACT, project.getPrimaryContact().toString());
        }
        em.persist(changeDelta);
        em.merge(project);
    }

}
